<template>
  <view class="apply_easypay_qrcode_step1 need_scroll_top_view">
    <steps :active="1"></steps>
    <scroll-view class="scroll-wrap" :scroll-y="true" :style="{height: (safeHeight - safeWidth / 375 * (101 + 64)) + 'px'}">
      <view class="form-wrap">
        <form>
          <view class="form-item self-border-bottom">
            <text class="form-item-label">商户类型</text>
            <picker :value="natureIndex" :range="storeNatureList" :disabled="isDisabled" range-key="name" @change="bindNaturePickerChange" class="form-item-pick">
              <view :class="{'pick-value': !storeNatureList[natureIndex].value, 'pick-value-select': storeNatureList[natureIndex].value}" v-if="storeNatureList && storeNatureList.length > 0">{{storeNatureList[natureIndex].name}}</view>
              <!-- <view class="pick-value" v-else>请选择商户类型</view> -->
            </picker>
            <view class="arrow"></view>
          </view>
          <view class="form-item self-border-bottom">
            <text class="form-item-label">门店名称</text>
            <input type="text" v-model="data.name" :disabled="isDisabled" class="form-item-input" :placeholder="namePlaceholder" placeholder-class="input-placeholder" @blur="backFixationTop()" />
            <!-- @blur="backFixationTop()" -->
            <view class="no-arrow"></view>
          </view>
          <view class="form-item">
            <text class="form-item-label">行业类别</text>
            <picker :value="tradeIndex" :range="tradeList" :disabled="isDisabled" range-key="name" @change="bindTradePickerChange" class="form-item-pick">
              <view :class="{'pick-value': !tradeList[tradeIndex].id, 'pick-value-select': tradeList[tradeIndex].id}" v-if="tradeList && tradeList.length > 0">{{tradeList[tradeIndex].name}}</view>
              <!-- <view class="pick-value" v-else>请选择行业类别</view> -->
            </picker>
            <view class="arrow"></view>
          </view>
          <view class="cut-line"></view>
          <view class="form-item self-border-bottom">
            <text class="form-item-label">所在城市</text>
            <picker :value="multiDistrictIndex" :disabled="isDisabled" range-key="name" :range="multiDistrictArray" @cancel="bindDistrictPickerCancel" @change="bindDistrictPickerChange" @columnchange="bindDistrictColumnPickerChange" class="form-item-pick" mode="multiSelector">
              <view class="pick-value-select" v-if="multiDistrictArray && multiDistrictArray.length > 0 && selectDistrict">
                <text v-if="multiDistrictArray[0] && multiDistrictArray[0][multiDistrictIndex[0]]">{{multiDistrictArray[0][multiDistrictIndex[0]].name}}</text>
                <text v-if="multiDistrictArray[1] && multiDistrictArray[1][multiDistrictIndex[1]]">{{multiDistrictArray[1][multiDistrictIndex[1]].name}}</text>
                <text v-if="multiDistrictArray[2] && multiDistrictArray[2][multiDistrictIndex[2]]">{{multiDistrictArray[2][multiDistrictIndex[2]].name}}</text>
              </view>
              <view class="pick-value" v-else>请选择您的所在城市</view>
            </picker>
            <view class="arrow"></view>
          </view>
          <view class="form-item">
            <text class="form-item-label">门店地址</text>
            <input type="text" adjust-position :disabled="isDisabled" v-model="data.address" class="form-item-input" placeholder="请选择您的门店地址" placeholder-class="input-placeholder" @blur="backFixationTop()"/>
            <view class="no-arrow"></view>
          </view>
          <view class="cut-line"></view>
          <view class="form-item">
            <text class="form-item-label">商户邮箱</text>
            <input type="text" v-model="data.email" :disabled="isDisabled" class="form-item-input" placeholder="请选择商户的邮箱地址" placeholder-class="input-placeholder" @blur="backFixationTop()"/>
            <view class="no-arrow"></view>
          </view>
          <!-- <view class="cut-line"></view>
          <view class="form-item">
            <text class="form-item-label">行业类别</text>
            <picker :value="tradeIndex" :range="tradeList" range-key="name" @change="bindTradePickerChange" class="form-item-pick">
              <view class="pick-value" v-if="tradeList && tradeList.length > 0">{{tradeList[tradeIndex].name}}</view>
            </picker>
            <view class="no-arrow"></view>
          </view> -->
          <view class="cut-line"></view>
          <view class="form-item-upload-wrap">
            <view class="form-item-head">
              <view class="title">
                门店外景照片
              </view>
              <view class="sample" @click="previewImg(1)">
                <text>示例</text>
              </view>
            </view>
            <view class="form-item-content" style="display: flex;">
              <view class="common-img-wrap" @click="uploadFile(1)">
                <view class="no-upload-img" v-if="!data.storePlateFileUrl || !data.storePlateFileId">
                  <image src="/static/image/qrcode/camera.png" mode="" class="img"></image>
                  <view class="text">
                    上传门店头照片
                  </view>
                </view>
                <view class="upload-img-wrap" v-else>
                  <image :src="data.storePlateFileUrl" mode="" class="upload-img"></image>
                </view>
              </view>
            </view>
          </view>
          <view class="form-item-upload-wrap" v-if="data.userType != 3">
            <view class="form-item-head">
              <view class="title">
                营业场所所租赁协议或者产权证明， 集中经营场所管理方出具的证明文件
              </view>
              <view class="sample">
                <text>示例</text>
              </view>
            </view>
            <view class="form-item-content" style="display: flex;">
              <view class="common-img-wrap" @click="uploadFile(2)">
                <view class="no-upload-img" v-if="!data.storeEquityFileUrl || !data.storeEquityFileId">
                  <image src="/static/image/qrcode/camera.png" mode="" class="img"></image>
                  <view class="text">
                    上传证明
                  </view>
                </view>
                <view class="upload-img-wrap" v-else>
                  <image :src="data.storeEquityFileUrl" mode="" class="upload-img"></image>
                </view>
              </view>
            </view>
          </view>
        </form>
      </view>
    </scroll-view>
    
    <view class="qrcode_selected_platform-footer">
      <button type="primary" class="qrcode_selected_platform-footer-btn" @click="submitInfo" v-if="status == null || status == 1">下一步</button>
      <button type="primary" class="qrcode_selected_platform-footer-btn" @click="nextStep" v-else>下一步</button>
    </view>
  </view>
</template>

<script>
import formValid from '@/unit/graceChecker.js'
import steps from '../common/steps.vue'
import { getDistrict } from '@/service/common/city.service.js'
import { multiDistrict, uploadFile, checkImage } from '@/unit/common.js'
import { getUserTypeSyncApi, getMccTypeSyncApi, getEasyPayInfoApi, getStoreInfoApi} from '@/service/qrCode/qrCode.service.js'
import { scrollToTargetPosition, setSafeAreaSize } from '@/mixin/index.mixin.js'
export default {
  mixins: [scrollToTargetPosition, setSafeAreaSize],
  components: {
    steps
  },
  data () {
    return {
      namePlaceholder: '请填写您的门店经营名称',
      status: null,
      storeNatureList: [], // 商户类型列表
      natureIndex: 0,
      selectNature: false,
      tradeList: [], // 行业类型列表
      tradeIndex: 0,
      selectTrade: false,
      selectDistrict: false,
      multiDistrictIndex: [], // 省市区选择的index
      multiDistrictArray: [], // 省市区数据 Array[Object]
      multiDistrictIds: [], // 省市区ID
      originMultiDistrictIndex: [], // 原始数据 用于取消选择省市区，还原原始数据
      originMultiDistrictArray: [], // 原始数据 用于取消选择省市区，还原原始数据
      originMultiDistrictIds: [], // 原始数据 用于取消选择省市区，还原原始数据
      data: {
        name: '', // 门店名称
        userType: null, // 商户类型
        businessProvince: '', // 省
        businessCity: null, // 市
        // 所在城市
        address: '', // 门店地址
        email: '', // 商户邮箱
        mccType: null, // 行业类别
        storePlateFileId: null, // 门头照片Id
        storePlateFileUrl: null, // 门头照片Url
        storeEquityFileId: null, // 产权照片Id
        storeEquityFileUrl: null, // 产权照片Url
      }
    }
  },
  computed: {
    isDisabled: function () {
      return this.status != null && this.status != 1;
    }
  },
  mounted () {},
  methods: {
    previewImg (type) { // 查看示例图片
      switch (type) {
      case 1:
        checkImage([this.$store.state.imgBaseUrl + '/esg_img/s-2.png'], 0);
        break;
      default:
      }
    },
    async initDistrictData (district) { // 初始化省市区数据
      let {multiDistrictArray, multiDistrictIndex, multiDistrictIds} = await multiDistrict.initMultDistrictArray({
        district: district,
        type: 2,
        length: 2
      });
      this.multiDistrictArray = multiDistrictArray;
      this.multiDistrictIndex = multiDistrictIndex;
      this.multiDistrictIds = multiDistrictIds;
      this.originMultiDistrictArray = JSON.parse(JSON.stringify(multiDistrictArray));
      this.originMultiDistrictIndex = JSON.parse(JSON.stringify(multiDistrictIndex));
      this.originMultiDistrictIds = JSON.parse(JSON.stringify(multiDistrictIds));
      this.data.businessProvince = this.multiDistrictIds[0];
      this.data.businessCity = this.multiDistrictIds[1];
    },
    bindDistrictPickerCancel (e) { // 取消省市区的选择
      this.multiDistrictArray = JSON.parse(JSON.stringify(this.originMultiDistrictArray));
      this.multiDistrictIndex = JSON.parse(JSON.stringify(this.originMultiDistrictIndex));
      this.multiDistrictIds = JSON.parse(JSON.stringify(this.originMultiDistrictIds));
    },
    bindDistrictPickerChange (e) { // 确认省市区的选择
      this.selectDistrict = true;
      this.originMultiDistrictArray = JSON.parse(JSON.stringify(this.multiDistrictArray));      
      this.originMultiDistrictIndex = JSON.parse(JSON.stringify(this.multiDistrictIndex));
      this.originMultiDistrictIds = JSON.parse(JSON.stringify(this.multiDistrictIds));
      this.data.businessProvince = this.multiDistrictIds[0];
      this.data.businessCity = this.multiDistrictIds[1];
    },
    async bindDistrictColumnPickerChange (e) { // 省市区的列发生变化
      if (e.detail.column < this.multiDistrictArray.length - 1) {
        let {multiDistrictArray, multiDistrictIndex, multiDistrictIds} = await multiDistrict.bindDistrictColumnPickerChange({
          column: e.detail.column,
          index: e.detail.value,
          multiDistrictIndex: JSON.parse(JSON.stringify(this.multiDistrictIndex)),
          multiDistrictArray: JSON.parse(JSON.stringify(this.multiDistrictArray)),
          type: 2
        });
        this.multiDistrictArray = multiDistrictArray;
        this.multiDistrictIndex = multiDistrictIndex;
        this.multiDistrictIds = multiDistrictIds;
      } else {
        this.multiDistrictIndex.splice(e.detail.column, 1, e.detail.value);
        this.multiDistrictIds.splice(e.detail.column, 1, this.multiDistrictArray[e.detail.column][e.detail.value].id);
      }
    },
    bindNaturePickerChange (e) {
      this.selectNature = true;
      this.natureIndex = e.detail.value;
      this.data.userType = this.storeNatureList[e.detail.value].value;
      this.namePlaceholder = this.natureIndex == 1 ? '请填写门店名称(请勿出现"公司"、"企业"字样)' : '请填写您的门店经营名称';
    },
    uploadFile (type) {
      if (this.status != null && this.status != 1) {
        return false;
      }
      uploadFile({
        success: (res) => {
          switch (type) {
          case 1:
            this.data.storePlateFileId = res.data.id;
            this.data.storePlateFileUrl = res.data.url;
            break;
          case 2:
            this.data.storeEquityFileId = res.data.id;
            this.data.storeEquityFileUrl = res.data.url;
            break;
          default:
          }
        }
      });
    },
    bindTradePickerChange (e) {
      this.selectTrade = true;
      this.tradeIndex = e.detail.value;
      this.data.mccType = this.tradeList[e.detail.value].id;
    },
    nextStep () {
      uni.navigateTo({
        url: '/pages/qrCode/applyEasypay/step2?userType=' + this.data.userType
      })
    },
    submitInfo () {
      let rule = [
        {name:'name', checkType : 'notnull', checkRule:'',  errorMsg:'请填写商户名称'},
        {name:'userType', checkType : 'notnull', checkRule:'',  errorMsg:'请选择商户类型'},
        {name:'businessProvince', checkType : 'notnull', checkRule:'',  errorMsg:'请选择所在城市省份'},
        {name:'businessCity', checkType : 'notnull', checkRule:'',  errorMsg:'请选择所在城市市'},
        {name:'address', checkType : 'notnull', checkRule:'',  errorMsg:'请填写地址'},
        // {name:'mobile', checkType : 'phoneno', checkRule:'',  errorMsg:'请填写正确的手机号'},
        // {name:'email', checkType : 'notnull', checkRule:'',  errorMsg:'请填写邮箱'},
        // {name:'email', checkType : 'email', checkRule:'',  errorMsg:'请填写正确的邮箱'},
        {name:'mccType', checkType : 'notnull', checkRule:'',  errorMsg:'请选择行业类别'},
        {name:'storePlateFileId', checkType : 'notnull', checkRule:'',  errorMsg:'请上传门店外景照片'}
      ];
      if (this.data.email) {
        rule.push({
          name:'email', checkType : 'email', checkRule:'',  errorMsg:'请填写正确的邮箱'
        });
      }
      if (this.data.userType != 3) {
        rule.push({
          name:'storeEquityFileId', checkType : 'notnull', checkRule:'',  errorMsg: '请上传店铺产权证明照片'
        });
      }
      var checkRes = formValid.check(this.data, rule);
      
      if (checkRes) {
        if (this.data.userType != 3) {
          if (this.data.name.indexOf('企业') !== -1 || this.data.name.indexOf('公司') !== -1) {
            uni.showToast({
              title: '门店名称里不要包含“企业”、“公司” 字样!',
              icon: 'none'
            })
            return false
          }
        }
        uni.setStorage({
          key: 'qrcode_step1_data',
          data: Object.assign(this.data, {
            districtIds: this.multiDistrictIds
          }),
          success: () => {
            uni.navigateTo({
              url: '/pages/qrCode/applyEasypay/step2?userType=' + this.data.userType
            })
          },
          fail: () => {
            uni.showToast({
              title: '存储信息失败，请重试！',
              icon: 'none'
            })
          }
        });
        
      } else {
        uni.showToast({ title: formValid.error, icon: "none" });
      }
    },
    async getEasypayInfo () {
      this.storeNatureList = await getUserTypeSyncApi({});
      if (this.storeNatureList && this.storeNatureList.length > 0) {
        this.storeNatureList.unshift({
          name: '请选择商户类型',
          value: ''
        })
      }
      this.tradeList = await getMccTypeSyncApi({});
      if (this.tradeList && this.tradeList.length > 0) {
        this.tradeList.unshift({
          id: null,
          name: '请选择行业类别'
        })
      }
      getEasyPayInfoApi({}, res => {
        if (res.status == 0 && res.data && res.data.id) {
          this.status = res.data.status;
          this.data.name = res.data.name; // 门店名称
          this.data.userType = res.data.userType; // 商户类型
          this.data.businessProvince = res.data.businessProvince; // 省
          this.data.businessCity = res.data.businessCity; // 市
          // 所在城市
          this.data.address = res.data.address; // 门店地址
          this.data.mobile = res.data.mobile; // 手机号
          this.data.email = res.data.email || ''; // 商户邮箱
          this.data.mccType = res.data.mccType; // 行业类别
          this.data.storePlateFileId = res.data.storeHeadImage.id; // 门头照片Id
          this.data.storePlateFileUrl = res.data.storeHeadImage.url; // 门头照片Url
          if (res.data.userType != 3) {
            this.data.storeEquityFileId = res.data.storeEquityFile.id; // 产权照片Id
            this.data.storeEquityFileUrl = res.data.storeEquityFile.url; // 产权照片Url
          }
          
          this.storeNatureList.forEach((item, index) => {
            if (this.data.userType === item.id) {
              this.selectNature = true;
              this.natureIndex = index;
            }
          });
          this.tradeList.forEach((item, index) => {
            if (this.data.mccType === item.id) {
              this.selectTrade = true;
              this.tradeIndex = index;
            }
          });
          this.selectDistrict = true;
          this.initDistrictData([this.data.businessProvince, this.data.businessCity]);
        } else if (res.status == 0 && !res.data) {
          this.init();
        }
      });
    },
    async init (option) {
      uni.getStorage({
        key: 'qrcode_step1_data',
        success: (res) => {
          this.data = res.data;
          this.storeNatureList.forEach((item, index) => {
            if (this.data.userType == item.id) {
              this.selectNature = true;
              this.natureIndex = index;
            }
          });
          this.tradeList.forEach((item, index) => {
            if (this.data.mccType === item.id) {
              this.selectTrade = true;
              this.tradeIndex = index;
            }
          });
          this.selectDistrict = true;
          this.initDistrictData(this.data.districtIds);
        },
        fail: () => {
          getStoreInfoApi({}, res => {
            if (res.status == 0) {
              this.data.name = res.data.name; // 门店名称
              this.data.address = res.data.address; // 门店地址
            }
          })
          this.data.userType = this.storeNatureList[0].id;
          this.data.mccType = this.tradeList[0].id;
          this.initDistrictData()
        }
      });
    }
  },
  mounted() {
    this.getEasypayInfo();
  }
}
</script>

<style lang="scss" scoped>
  .apply_easypay_qrcode_step1 {
    position: relative;
    height: calc(100vh);
    padding-bottom: constant(safe-area-inset-bottom);  
    padding-bottom: env(safe-area-inset-bottom);  
    .scroll-wrap {
      height: calc(100vh - 52px - 101px);
    }
    .form-wrap {
      margin-top: 20rpx;
      background: #FFFFFF;
      .self-border-bottom {
        border-bottom: 1rpx solid #E1E1E1;
      }
      .self-margin-top {
        margin-top: 22rpx;
      }
      .cut-line {
        height: 22rpx;
        background-color: #FAFAFA;
      }
      
      .pick-value-select {
        color: #333333;
        font-size: 28rpx;
      }
      
      .pick-value {
        color: #999999;
        font-size: 24rpx;
      }
      .form-item {
        display: flex;
        width: 718rpx;
        // justify-content: center;
        align-items: center;
        margin-left: 32rpx;
        // height: 100rpx;
        padding: 36rpx 0;
        
        .form-item-label {
          width: 140rpx;
          text-align: left;
          padding: 0 32rpx 0 0;
          font-size: 28rpx;
          color: #333333;
          font-weight:500;
        }
        .form-item-input {
          font-size: 28rpx;
          height: 38rpx;
          color: #333333;
          flex: 1;
          .input-placeholder {
            font-size: 24rpx;
            color: #999999;
          }
        }
        .form-item-pick {
          flex: 1;
        }
        .arrow {
          margin-right: 33rpx;
          border-right: 3rpx solid #8A8A8A;
          border-top: 3rpx solid #8A8A8A;
          height: 18rpx;
          width: 18rpx;
          transform: rotate(45deg);
          -webkit-transform: rotate(45deg);
          /*不加这两个属性三角会比上一个略丑, 大家可以试一下*/
          border-left: 2rpx solid transparent;
          border-bottom: 2rpx solid transparent;
        }
        .no-arrow {
          margin-left: 64rpx;
        }
      }
      
      .form-item-upload-wrap {
        background-color: #FFFFFF;
        padding: 0 34rpx 22rpx;
        .form-item-head {
          overflow: hidden;
          padding-top: 40rpx;
          display: flex;
          justify-content: space-between;
          .title {
            // float: left;
            flex: 1;
            color: #333333;
            font-size: 36rpx;
          }
          .sample {
            width: 60rpx;
            // float: right;
            text {
              color: #FF7473;
              font-size: 28rpx;
              text-decoration: underline;
            }
          }
          &:after {
            clear: both;
          }
        }
        .form-item-content {
          margin-top: 30rpx;
          .common-img-wrap {
            width: 330rpx;
            height: 200rpx;
            border: 1px dashed #E1E1E1;
            border-radius: 16rpx;
            
            .no-upload-img {
              width: 100%;
              height: 100%;
              display: flex;
              flex-flow: column;
              align-items: center;
              justify-content: center;
              .img {
                width: 80rpx;
                height: 80rpx;
              }
              .text {
                margin-top: 29rpx;
                color: #666666;
                font-size: 24rpx;
                font-weight:500;
              }
            }
            
            .upload-img-wrap {
              width: 100%;
              height: 100%;
              
              .upload-img {
                width: 100%;
                height: 100%;
                border-radius: 16rpx;
              }
            }
          }
        }
      }
    }
    
    .qrcode_selected_platform-footer {
      position: absolute;
      bottom: 0rpx;
      left: 0rpx;
      width: 100%;
      height: 125rpx;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      border-top: 1rpx solid #E1E1E1;
      background: #FFFFFF;
      .qrcode_selected_platform-footer-btn {
        width: 687rpx;
        height: 90rpx;
        line-height: 90rpx;
        background-color: #434343;
        color: #F6DA99;
        font-size: 30rpx;
      }
    }
    
  }
</style>
